package com.itheima.controller;

import com.itheima.exception.TliasException;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/depts")
@RestController
@Slf4j
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpMapper empMapper;

    @GetMapping
    public Result deptSelect(){
        log.info("查询部门");
        List<Dept> depts = deptService.list();
        return Result.success(depts);
    }

    @DeleteMapping
    public Result deptDelete(Integer id){
        log.info("删除部门:"+id);
        Integer count = empMapper.getEmpCountById(id);
        if (count > 0){
            throw new TliasException("对不起,当前部门下已有员工,不能直接删除");
        }
        deptService.removeById(id);
        return Result.success();
    }

    @PostMapping
    public Result deptInsert(@RequestBody Dept dept){
        log.info("添加部门");
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptService.save(dept);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result deptSelectById(@PathVariable Integer id){
        log.info("回显部门信息");
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    @PutMapping
    public Result deptUpdate(@RequestBody Dept dept){
        log.info("修改部门信息");
        dept.setUpdateTime(LocalDateTime.now());
        deptService.updateById(dept);
        return Result.success();
    }
}
